<script setup lang="ts">
import { ref } from 'vue'
import CustomNavbar from './components/CustomNavbar.vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import { onLoad } from '@dcloudio/uni-app'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import type { XtxGuessInstance } from '@/types/component'
import PageSkeleton from './components/PageSkeleton.vue'

/* *定义一个轮播图列表*/
const bannerList = ref<BannerItem[]>([])
/* *定义一个分类列表*/
const categoryList = ref<CategoryItem[]>([])
/**定义一个热门推荐列表 */
const hotList = ref<HotItem[]>([])
/**
 * 功能：获取首页轮播图数据
 */
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}
/**
 * 功能：获取首页分类数据
 */
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}
/**
 * 功能：获取首页热门推荐数据
 */
const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}
//加载中标记
const isLoading = ref(false)
/**页面加载的钩子函数 */
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})

//获取猜你喜欢组件实例
const guessRef = ref<XtxGuessInstance>()
// 滚动触底事件
const onScrolltolower = () => {
  guessRef.value?.getMore()
}

// 下拉刷新状态
const isTriggered = ref(false)
//自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  //开启动画
  isTriggered.value = true
  guessRef.value?.resetData()
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  //关闭动画
  isTriggered.value = false
}
</script>

<template>
  <view class="viewport">
    <!--自定义导航栏-->
    <CustomNavbar />
    <!--滑动容器-->
    <scroll-view
      scroll-y
      class="scroll-view"
      @scrolltolower="onScrolltolower"
      refresher-enabled
      @refresherrefresh="onRefresherrefresh"
      :refresher-triggered="isTriggered"
    >
      <PageSkeleton v-if="isLoading" />
      <template v-else>
        <!--轮播图-->
        <XtxSwiper :list="bannerList" />
        <!--前台分类-->
        <CategoryPanel :list="categoryList" />
        <!--热门推荐-->
        <HotPanel :list="hotList" />
        <!-- 猜你喜欢 -->
        <XtxGuess ref="guessRef"></XtxGuess>
      </template>
    </scroll-view>
  </view>
</template>

<style lang="scss">
//
page {
  background-color: #f7f7f7;
  height: 100%;
  overflow: hidden;
}

.viewport {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll-view {
  flex: 1;
  overflow: hidden;
}
</style>
